package com.slkj.shilixiaoyuanapp.data;

import android.content.Intent;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.slkj.shilixiaoyuanapp.SlxyApplication;
import com.slkj.shilixiaoyuanapp.data.room.AppDataBase;
import com.slkj.shilixiaoyuanapp.data.room.dao.UserDao;
import com.slkj.shilixiaoyuanapp.entity.UserDataBaseEntity;
import com.slkj.shilixiaoyuanapp.entity.UserEntity;
import com.slkj.shilixiaoyuanapp.ui.user.LoginActivity;

import cn.jpush.android.api.JPushInterface;

/**
 * Created  on 2018-07-30
 *
 * @author 唐开阔
 * @describe
 */
public class UserRequest {
    private static final UserRequest ourInstance = new UserRequest();
    private UserEntity user;
    private UserDao userDao;
    public static UserRequest getInstance() {
        return ourInstance;
    }

    private UserRequest() {
        userDao = AppDataBase.getInstance().getUserDao();
        if (userDao.getUserJson() == null){
            user = null;
        }
        else {
            String userJson = userDao.getUserJson().getJson();
            Gson gson = new Gson();
            user = gson.fromJson(userJson,UserEntity.class);
        }
    }

    public UserEntity getUser() {
        return user;
    }

    /**
     * 保存对象
     */
    public void setUser(UserEntity newUser) {
        if (isLogin()){
            userDao.delete(userDao.getUserJson());
        }
        Gson gson = new Gson();
        userDao.insert(new UserDataBaseEntity(gson.toJson(newUser)));
        user = newUser;
    }

    /**
     * 退出登录
     * 更新对象
     */
    public void exitLogon() {
        if (isLogin()) {
            userDao.delete(userDao.getUserJson());
            user = null;
            JPushInterface.deleteAlias(SlxyApplication.getContext(), 1);
            SlxyApplication.getContext().startActivity(new Intent(SlxyApplication.getContext(), LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
        }
    }


        public boolean isLogin(){
        return user != null;
    }
}
